<template>
  <div class="page-edit">
    <a-form
      ref="formRef"
      :model="formState"
      :rules="formRules"
      :labelCol="{ style: { width: '84px' } }"
      :colon="false"
      labelAlign="right"
    >
      <div class="page-edit-common">
        <a-form-item label="广告名称" name="name">
          <a-input v-model:value.trim="formState.name" :maxlength="30" placeholder="请输入广告标题" class="w-[359px]" />
        </a-form-item>
        <a-form-item label="图文类型" name="img_type" class="mb-0">
          <div>
            <a-radio-group v-model:value="formState.img_type" @change="handleTypeChange">
              <a-radio :value="1">图片文件上传</a-radio>
              <a-radio :value="2" class="ml-[55px]">图片URL</a-radio>
              <a-radio :value="3" class="ml-[55px]">文字</a-radio>
            </a-radio-group>
            <div>
              <a-form-item :name="formState.img_type === 3 ? '' : 'img_url'">
                <div class="flex items-center">
                  <UploadImage v-if="formState.img_type === 1" fileType="0" imgType="4" @getImageInfo="getImageInfo">
                    <a-input-search
                      v-model:value="formState.img_url"
                      enter-button="上传文件"
                      @search="onSearch"
                      readOnly
                      class="w-[359px]"
                    />
                  </UploadImage>
                  <a-input
                    v-else-if="formState.img_type === 2"
                    v-model:value="formState.img_url"
                    placeholder="请输入URL地址"
                    class="w-[359px]"
                    @blur="handleBlur"
                  />
                  <div class="text-preview" v-else>
                    <div class="text-preview-inputBox">
                      <a-form-item name="img_url">
                        <a-textarea
                          maxlength="50"
                          class="text-preview-inputBox-input"
                          v-model:value="formState.img_url"
                          placeholder="请输入"
                        />
                      </a-form-item>
                      <span class="text-preview-inputBox-text">预览></span>
                      <div
                        class="text-preview-inputBox-input mb-[24px] overflow-auto whitespace-pre-wrap"
                        :style="(styleObj as any)"
                      >
                        <div class="flex-1">
                          {{ formState.img_url }}
                        </div>
                      </div>
                    </div>
                    <div class="text-preview-itemBox">
                      <div class="text-preview-itemBox-lineOne">
                        <div class="common-item">
                          <span class="common-item-title">字体大小：</span>
                          <a-select
                            v-model:value="jsonState.fontSize"
                            class="w-[50px]"
                            :options="FONT_SIZE.map((item) => ({ value: item }))"
                            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
                          >
                          </a-select>
                        </div>
                        <div class="common-item">
                          <span class="common-item-title ml-[50px]">字体颜色：</span>
                          <ColorPickerField
                            @colorChange="colorChange"
                            :schema="{ defaultValue: jsonState.color, tag: 'color' }"
                            changeFuncName="colorChange"
                          />
                        </div>
                        <div class="common-item">
                          <span class="common-item-title ml-[67px]">是否加粗：</span>
                          <a-radio-group v-model:value="jsonState.fontWeight">
                            <a-radio value="bold">是</a-radio>
                            <a-radio value="normal" class="ml-[62px]">否</a-radio>
                          </a-radio-group>
                        </div>
                      </div>
                      <div class="text-preview-itemBox-lineTwo">
                        <div class="common-item">
                          <span class="common-item-title">背景高度：</span>
                          <a-select
                            v-model:value="jsonState.height"
                            class="w-[50px]"
                            :options="BACKGROUND_HEIGHT.map((item) => ({ value: item }))"
                            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
                          >
                          </a-select>
                        </div>
                        <div class="common-item">
                          <span class="common-item-title ml-[50px]">背景颜色：</span>
                          <ColorPickerField
                            @bgColorChange="bgColorChange"
                            :schema="{ defaultValue: jsonState.background, tag: 'color' }"
                            changeFuncName="bgColorChange"
                          />
                        </div>
                        <div class="common-item">
                          <span class="common-item-title ml-[67px]">对齐方式：</span>
                          <a-form-item class="mb-0">
                            <a-radio-group v-model:value="jsonState.textAlign">
                              <a-radio value="left">靠左对齐</a-radio>
                              <a-radio value="center" class="ml-[20px]">居中对齐</a-radio>
                              <a-radio value="right" class="ml-[20px]">靠右对齐</a-radio>
                            </a-radio-group>
                          </a-form-item>
                        </div>
                      </div>
                    </div>
                  </div>
                  <a-tooltip
                    v-if="(formState.img_type === 2 || formState.img_type === 1) && previewImage"
                    placement="right"
                    class="ml-[16px]"
                    color="#fff"
                  >
                    <template #title>
                      <img
                        alt="example"
                        class="max-w-[300px] max-h-[300px] w-[-webkit-fill-available]"
                        :src="previewImage"
                      />
                    </template>
                    <a href="javascript:;" class="flex items-center">
                      <i class="iconfont icon-guanggao text-[18px] mr-[5px]"></i>
                      预览
                    </a>
                  </a-tooltip>
                </div>
                <div v-if="formState.img_type !== 3" class="source-introduce">
                  {{ storage.get('img_type') ? '支持' + storage.get('img_type') + '素材，' : '' }}
                  {{ storage.get('img_size') ? storage.get('img_size') + '以内；' : '' }}建议尺寸686*146px
                </div>
              </a-form-item>
            </div>
          </div>
        </a-form-item>

        <div class="flex">
          <a-form-item label="跳转链接" name="jump_addr">
            <a-input
              v-model:value="formState.jump_addr"
              placeholder="请输入https://或http://开头的链接"
              class="w-[359px]"
            />
          </a-form-item>
        </div>
        <a-form-item label="状态" name="status" class="page-edit-common-form-item">
          <a-radio-group v-model:value="formState.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="2" class="ml-[82px]">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </div>
    </a-form>
    <div class="page-edit-button">
      <a-button type="primary" @click="saveSite">保存广告</a-button>
      <a-button @click="() => $router.back()">返回</a-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, computed, inject } from 'vue'
import UploadImage from '@/components/components/upload-image/UploadImage.vue'
import { useRouter } from 'vue-router'
import { FONT_SIZE, BACKGROUND_HEIGHT } from './dataSource'
import ColorPickerField from '@/components/components/color-picker/ColorPickerField'
import { formRules } from '../state'
import apis from '@/apis'
import { message } from 'ant-design-vue'
import { storage } from '@/utils/storage'
const {
  advertising: { add, update, detail }
} = apis
const baseUrl: any = inject('baseUrl')
const router = useRouter()
const formRef = ref()
const previewImage = ref('')
const advertisingId = ref()
//表单数据
interface IState {
  id?: string
  library_id?: string | undefined
  adv_type: number
  name: string
  img_type: number //图片或者文字
  img_url: string
  word_style: string
  jump_addr: string //跳转链接
  status: number | undefined
  checkAll: boolean
  [key: string]: any
}
const formState = reactive<IState>({
  checkAll: true,
  adv_type: 8,
  name: '',
  img_type: 1,
  img_url: '',
  word_style: '',
  jump_addr: '',
  status: 1
})
//文字json
const jsonState = reactive({
  color: 'rgb(0,0,0)',
  fontSize: 12, //字体大小
  fontWeight: 'normal', //是否加粗
  height: 150, //背景高度
  background: 'rgba(255,255,255,1)', //背景颜色
  textAlign: 'center' //对齐方式
})
const styleObj = computed(() => {
  return {
    fontSize: jsonState.fontSize + 'px',
    color: jsonState.color,
    fontWeight: jsonState.fontWeight,
    height: jsonState.height + 'px',
    background: jsonState.background,
    // textAlign: jsonState.justifyContent,
    // lineHeight: jsonState.background + 'px'
    display: 'flex',
    alignItems: 'center',
    textAlign: jsonState.textAlign,
    whiteSpace: 'pre-line'
  }
})
//图文类型切换事件
const handleTypeChange = (e: any) => {
  console.log('e: ', e)
  formState.img_url = ''
  previewImage.value = ''
}
//字体颜色事件
const colorChange = (val: string) => {
  console.log('val: ', val)
  jsonState.color = val.replace(/\s/g, '')
}
//背景颜色事件
const bgColorChange = (val: string) => {
  console.log('val: ', val)
  jsonState.background = val.replace(/\s/g, '')
  console.log('jsonState.background: ', jsonState.background)
}

const saveSite = () => {
  formRef.value
    .validate()
    .then(() => {
      if (formState.img_type === 3) {
        formState.word_style = JSON.stringify(styleObj.value)
      }
      if (!advertisingId.value) {
        formState.library_id = storage.get('libraryId')
        add(formState).then((res: any) => {
          message.success('添加成功')
          router.back()
        })
      } else {
        formState.id = advertisingId.value
        update(formState).then((res: any) => {
          message.success('编辑成功')
          router.back()
        })
      }
    })
    .catch((err: any) => {
      console.log(err, ':err')
    })
}
const onSearch = (searchValue: string) => {
  console.log('use value', searchValue)
}
const handleBlur = (e: any) => {
  previewImage.value = e.target.value
}
const getImageInfo = (value: any) => {
  console.log('value: ', value)
  formState.img_url = value
  formRef.value.clearValidate(['img_url'])
  if (formState.img_type === 1) return (previewImage.value = baseUrl + value)
  previewImage.value = value
}
const getAdDetail = () => {
  detail({ id: advertisingId.value }).then((res: any) => {
    const { name, img_type, img_url, jump_addr, word_style, status, show_position } = res.advertising
    formState.name = name
    formState.img_type = img_type
    formState.jump_addr = jump_addr
    formState.img_url = img_url
    if (img_type === 3) {
      const styleObj = JSON.parse(word_style.replace(/px/g, ''))
      console.log('styleObj: ', styleObj)
      const { whiteSpace, height, ...styles } = styleObj
      Object.assign(jsonState, styles)
      jsonState.height = +height
    }
    formState.status = status
    formState.show_position = show_position
    console.log(res, '启动广告详情')
    if (img_url) {
      if (img_type === 1) {
        previewImage.value = baseUrl + img_url
      } else {
        previewImage.value = img_url
      }
    }
  })
}
onMounted(() => {
  console.log(router.currentRoute.value.query, 'query')
  advertisingId.value = router.currentRoute.value.query.id
  if (!advertisingId.value) return false
  getAdDetail()
})
</script>

<style lang="less" scoped>
.page-edit {
  // width: 1200px;

  .ant-form {
    .page-edit-common {
      min-height: 205px;
      padding-top: 20px;
      box-sizing: border-box;
      border-bottom: 1px solid #f0f0f0;

      //select无边框
      :deep(.ant-select-single:not(.ant-select-customize-input) .ant-select-selector) {
        padding: 0;
        border: none;
        background-color: unset;
      }

      .text-preview {
        &-inputBox {
          display: flex;
          align-items: center;
          font-size: 12px;
          color: #bfbfbf;

          &-text {
            margin: 0 8px;
          }

          &-input {
            width: 359px;
            height: 150px;
            border: 1px solid rgba(217, 217, 217, 1);
            border-radius: 3px;
          }
        }

        &-itemBox {
          width: 766px;
          height: 96px;
          display: flex;
          flex-direction: column;
          flex-wrap: wrap;
          justify-content: space-between;
          background-color: #f9f9f9;
          border-radius: 3px;
          padding: 16px 0px 16px 22px;
          box-sizing: border-box;
          font-size: 14px;
          color: #262626;

          .common-item {
            min-width: 128px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;

            &-title {
              width: 76px;
            }

            :deep(.vc-color-wrap) {
              width: 28px;
            }

            .no-margin-bottom {
              margin: 0;
            }

            .ant-radio-wrapper,
            .ant-radio-group {
              margin: 0;
            }
          }

          &-lineOne {
            display: flex;
            align-items: center;
          }

          &-lineTwo {
            display: flex;
            align-items: center;
          }
        }
      }

      &-title {
        font-size: 16px;
        color: #262626;
        letter-spacing: 1.14px;
        font-weight: 500;
        margin: 0 0 24px 0;
      }

      .source-introduce {
        margin-top: 8px;
        font-size: 12px;
        color: #bfbfbf;
      }

      :deep(.ant-radio-group) {
        margin: 5px 0 13px;
      }
    }
  }

  &-button {
    margin-top: 24px;
    display: flex;

    button:nth-child(1) {
      margin-right: 16px;
    }
  }
}
</style>
